package com.yunfinal.api.tpl.template.directive;

import com.jfinal.core.JFinal;
import com.jfinal.log.Log;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.expr.ast.Id;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;

/**
 * #try(默认值Exception可设置)
 * 包裹代码
 * #end
 * #if(Exception)
 * #(e.getMessage())
 * #end
 */
public class TryDirective extends Directive {
    private static final Log log = Log.getLog(TryDirective.class);
    protected String exceptionName = "Exception";
    protected String name;

    @Override
    public void setExprList(ExprList exprList) {
        Expr[] exprArray = exprList.getExprArray();
        if (exprArray.length == 0) {
            return;
        }
        if ((exprArray[0] instanceof Id)) {
            this.name = ((Id) exprArray[0]).getId();
        }
    }

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        try {
            stat.exec(env, scope, writer);
        } catch (Exception e) {
            if (JFinal.me().getConstants().getDevMode()) {
                log.error("异常" ,e);
            }
            setDefaultName(exceptionName);
            scope.set(this.name, e);
        }
    }

    @Override
    public boolean hasEnd() {
        return true;
    }

    protected void setDefaultName(String name) {
        if (this.name == null) {
            this.name = name;
        }
    }
}
